import React, { memo } from 'react'
import { useDispatch, useSelector } from 'react-redux'

import { View, Button, Text } from '@tarojs/components'

import { CountState, RootState } from '@/reducers/data'
import styles from './index.module.scss'

// #region 书写注意
//
// 目前 typescript 版本还无法在装饰器模式下将 Props 注入到 Taro.Component 中的 props 属性
// 需要显示声明 connect 的参数类型并通过 interface 的方式指定 Taro.Component 子类的 props
// 这样才能完成类型检查和 IDE 的自动提示
// 使用函数模式则无此限制
// ref: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/20796
//
// #endregion

type PageStateProps = {
  counter: {
    num: number
  }
}

type PageDispatchProps = {
  add: () => void
  dec: () => void
  asyncAdd: () => void
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps & PageState

interface Index {
  props: IProps
}

const Index: React.FC<IProps> = memo(() => {
  const counter: CountState = useSelector((state: RootState) => state.counter)
  const dispatch = useDispatch()

  const add = () => dispatch({ type: 'counter/add' })
  const dec = () => dispatch({ type: 'counter/minus' })
  const asyncAdd = () => {
    setTimeout(() => {
      dispatch({ type: 'counter/add' })
    }, 1000)
  }

  return (
    <View className={styles.index}>
      <View style={{ textAlign: 'center' }}>
        <Text>{`当前计数器的值：${counter.num}`}</Text>
      </View>
      <van-divider />
      <van-button type='warning' block onClick={add}>
        +
      </van-button>
      <van-divider />
      <van-button type='primary' block onClick={dec}>
        -
      </van-button>
      <van-divider />
      <van-button type='info' block onClick={asyncAdd}>
        延时一秒后加一
      </van-button>

      <View></View>
    </View>
  )
})

export default Index
